//
//  LJHPlayerViewController.m
//  HEARME
//
//  Created by mac on 16/1/27.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "LJHPlayerViewController.h"
#import "LJHTrackModel.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "LJHPlayListViewController.h"
#import "LJHAuthorDetailViewController.h"
#import <MediaPlayer/MediaPlayer.h>

@interface LJHPlayerViewController ()<UMSocialUIDelegate>

@property(nonatomic,retain)UIImageView *ownerAvator;
@property(nonatomic,retain)UILabel *ownerName;
@property(nonatomic,retain)UILabel *ownerInfo;
@property(nonatomic,assign)NSInteger uid;

@property(nonatomic,retain)NSMutableDictionary *dict; //锁屏字典


@end

@implementation LJHPlayerViewController

- (void)dealloc
{
    int array[] = {1,3,4,6,7};
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j<5-1-i; j++) {
            int t = 0;
            if (array[j]<array[j+1]) {
                t = array[j];
                array[j] = array[j+1];
                array[j+1] = t;
            }
        }
    }
    
    
    [_playTimer release];
    [_playerView release];
    [_currentTimeLabel release];
    [_allMusicArray release];
    [_player release];
    [_ownerAvator release];
    [_ownerName release];
    [_ownerInfo release];
    [_dict release];
    [super dealloc];
    
}

//将player页设成单例
+(instancetype)sharaMusicPlayer
{
    
    static LJHPlayerViewController *playerVC = nil;
    static dispatch_once_t onceToken; //整个程序的执行周期中，此block块只执行一次
    dispatch_once(&onceToken, ^{
        
        playerVC = [[LJHPlayerViewController alloc] init];
        
    });
   
    return playerVC;
    
}

-(void)viewWillAppear:(BOOL)animated //根据状态判断播放按钮图标
{
    
    [super viewWillAppear:animated];
    if (self.player.state == STKAudioPlayerStatePlaying) {
        [self.playerView.playButton setImage:[UIImage imageNamed:@"toolbar_pause_h_p"] forState:UIControlStateNormal];
    }
    else if (self.player.state == STKAudioPlayerStatePaused)
    {
        [self.playerView.playButton setImage:[UIImage imageNamed:@"toolbar_play_n_p"] forState:UIControlStateNormal];
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.dict = [NSMutableDictionary dictionary];

    self.view.backgroundColor = [UIColor whiteColor];
    
    self.playerView = [[LJHPlayerView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.view addSubview:self.playerView];
    [self createSubviews];
    
    //equalizerBandFrequencies均衡器带频率
    //enableVolumeMixer设置为yes,将启用音量控制
    //flushQueueOnSeek 刷新音频队列
    
    self.player = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }];
    
    self.player.volume = 0.5;
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(10, 40, 40, 30);
    backButton.backgroundColor = [UIColor clearColor];
    [backButton setImage:[UIImage imageNamed:@"navidrop_arrow_down_n@2x.png"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"navidrop_arrow_down_h@2x.png"] forState:UIControlStateHighlighted];
    
    
    UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    moreButton.frame = CGRectMake(0, 0, 40, 30);
    moreButton.backgroundColor = [UIColor clearColor];
    [moreButton setImage:[UIImage imageNamed:@"icon_more_n@2x.png"] forState:UIControlStateNormal];
    [moreButton setImage:[UIImage imageNamed:@"icon_more_h@2x.png"] forState:UIControlStateHighlighted];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:moreButton];
    
    [[NSUserDefaults standardUserDefaults] setObject:@"单曲循环" forKey:@"playMode"];
    
#pragma mark - 各种按钮方法
    [moreButton addTarget:self action:@selector(moreBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView.upButton addTarget:self action:@selector(upButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView.nextButton addTarget:self action:@selector(nextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView.playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView.listButton addTarget:self action:@selector(listButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.playerView.progressSlider addTarget:self action:@selector(progressSliderAction:) forControlEvents:UIControlEventValueChanged];
    [self.playerView.historyButton addTarget:self action:@selector(historyButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark - 创建子视图

-(void)createSubviews
{
    self.ownerAvator = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH*0.018, self.playerView.playBarView.frame.origin.y+self.playerView.playBarView.frame.size.height+WIDTH*0.05, WIDTH*0.18, WIDTH*0.18)];
    self.ownerAvator.backgroundColor = [UIColor clearColor];
    self.ownerAvator.layer.masksToBounds = YES;
    self.ownerAvator.layer.cornerRadius = WIDTH*0.09;
    [self.view addSubview:self.ownerAvator];
    [_ownerAvator release];
    self.ownerAvator.userInteractionEnabled = YES;
    
    self.ownerName = [[UILabel alloc] initWithFrame:CGRectMake(self.ownerAvator.frame.origin.x+self.ownerAvator.frame.size.width+WIDTH*0.03, self.ownerAvator.frame.origin.y, WIDTH*0.5, self.ownerAvator.frame.size.height*0.4)];
    self.ownerName.backgroundColor = [UIColor clearColor];
    self.ownerName.font = [UIFont systemFontOfSize:15 weight:1];
    [self.view addSubview:self.ownerName];
    [_ownerName release];
    
    self.ownerInfo = [[UILabel alloc] initWithFrame:CGRectMake(self.ownerAvator.frame.origin.x+self.ownerAvator.frame.size.width+WIDTH*0.03, self.ownerName.frame.size.height+self.ownerName.frame.origin.y+ HEIGHT*0.01, WIDTH*0.7, self.ownerAvator.frame.size.height*0.4)];
    self.ownerInfo.backgroundColor = [UIColor clearColor];
    self.ownerInfo.font = [UIFont systemFontOfSize:13 weight:0];
    self.ownerInfo.textColor = [UIColor lightGrayColor];
    [self.view addSubview:self.ownerInfo];
    [_ownerInfo release];
    
    UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    shareBtn.frame = CGRectMake(WIDTH-WIDTH/10-20, HEIGHT-WIDTH/10-30, WIDTH/10, WIDTH/10);
    [shareBtn setImage:[UIImage imageNamed:@"iconfont-fenxiang"] forState:UIControlStateNormal];
    [self.view addSubview:shareBtn];
    [shareBtn addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark - 分享按钮

-(void)shareBtnAction:(UIButton *)btn
{
    
    NSString *string = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%ld", (long)self.song_id];
    
    // afn获取数据
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url_string = string;
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        
        NSMutableDictionary *dictionary = responseObject;
        
        LJHAlbumModel *playData = [LJHAlbumModel modelWithDictionary:dictionary];
        
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"558936d367e58eb81b001298"
                                          shareText:playData.playUrl64
                                         shareImage:playData.coverLarge
                                    shareToSnsNames:@[UMShareToWechatSession,UMShareToWechatTimeline,UMShareToWechatFavorite,UMShareToSina]
                                           delegate:self];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"您的设备无网络访问" message:nil preferredStyle:UIAlertControllerStyleAlert];
        
        [self presentViewController:alertC animated:YES completion:^{
            
        }];
        
        UIAlertAction *cancelButton = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alertC addAction:cancelButton];
        
    }];
    
    
        
    
}

//实现回调方法（可选）：
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}

#pragma mark - 选择播放模式
-(void)moreBtnAction:(UIButton *)btn
{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"选择播放模式" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    [self presentViewController:alertC animated:YES completion:^{
        
    }];
    
    UIAlertAction *singleCicle = [UIAlertAction actionWithTitle:@"单曲循环" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [[NSUserDefaults standardUserDefaults] setObject:@"单曲循环" forKey:@"playMode"];
        
    }];
    
    UIAlertAction *queuePlay = [UIAlertAction actionWithTitle:@"顺序播放" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [[NSUserDefaults standardUserDefaults] setObject:@"顺序播放" forKey:@"playMode"];
        
    }];
    
    UIAlertAction *randomAction = [UIAlertAction actionWithTitle:@"随机播放" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [[NSUserDefaults standardUserDefaults] setObject:@"随机播放" forKey:@"playMode"];
        //        NSLog(@"%@", [[NSUserDefaults standardUserDefaults] objectForKey:@"playMode"]);
    }];
    
    [alertC addAction:singleCicle];
    [alertC addAction:queuePlay];
    [alertC addAction:randomAction];
    
}

#pragma mark - 查看作者声音
-(void)tapAction:(UITapGestureRecognizer *)tap
{
    
    LJHAuthorDetailViewController *authorDetailVC = [[LJHAuthorDetailViewController alloc] init];
    
//    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:authorDetailVC];
    authorDetailVC.uid = self.uid;
    [self presentViewController:authorDetailVC animated:YES completion:^{
        
        
    }];
    
}

#pragma mark - 播放，暂停
-(void)playButtonAction:(UIButton *)btn
{
    if (self.player.state == STKAudioPlayerStatePlaying) {
        [self.player pause];
        [self.playTimer invalidate]; //self.playTimer废弃
        [self.playerView.playButton setImage:[UIImage imageNamed:@"toolbar_play_n_p@2x.png"] forState:UIControlStateNormal];
        
        
    }
    else if (self.player.state == STKAudioPlayerStatePaused)
    {
        [self.player resume];
        [self.playerView.playButton setImage:[UIImage imageNamed:@"toolbar_pause_h_p@2x.png"] forState:UIControlStateNormal];
        
    }
    else
    {
        
//        [self playMusic];
        btn.enabled = YES;
        
    }
    
    btn.selected = !btn.selected;
    
}

#pragma mark - 返回
-(void)backButtonAction:(UIButton *)btn
{
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}

#pragma mark - 上一首
-(void)upButtonAction:(UIButton *)btn
{
    
    if (self.indexRow != 0) {
        
        self.indexRow = (self.indexRow - 1);
        
    }
    else
    {
        btn.enabled = NO;
    }
    
    LJHTrackModel *sing = [self.allMusicArray objectAtIndex:self.indexRow];
    self.song_id = sing.trackId;
    
}

#pragma mark - 下一首
-(void)nextButtonAction:(UIButton *)btn
{
    //+1后对总数取余是为了防止点击多次,数组越界
    
    if (self.allMusicArray.count == 0) {
        [self playMusic];
    }
    else
    {
        self.indexRow = (self.indexRow + 1)%self.allMusicArray.count;
        
        //如果歌曲总数大于当前播放的音乐下标
        if (self.indexRow < self.allMusicArray.count) {
            
            LJHTrackModel *singleM = [self.allMusicArray objectAtIndex:self.indexRow];
            NSLog(@"%ld", (long)singleM.trackId);
            self.song_id = singleM.trackId;
            
        }
        else
        {
            
            //如果总数小于当前下标,直接播放取余数后的.也就是从第一首歌开始播放,用户体验是循环播放了
            [self playMusic];
            
        }
        self.playerView.upButton.enabled = YES;
        
    }
}

#pragma mark - 播放列表
-(void)listButtonAction:(UIButton *)btn
{
    LJHPlayListViewController *playListVC = [[LJHPlayListViewController alloc] init];
    playListVC.playArray = self.allMusicArray;
    playListVC.kind = @"播放列表";
    [self presentViewController:playListVC animated:YES completion:^{
        
        
    }];
}

#pragma mark - 播放历史
-(void)historyButtonAction:(UIButton *)btn
{
    LJHPlayListViewController *playListVC = [[LJHPlayListViewController alloc] init];
    playListVC.playArray = [[LJHFMData shareFMDB] selectTrackData];
    playListVC.kind = @"播放历史";
    [self presentViewController:playListVC animated:YES completion:^{
        
        
    }];
}

#pragma mark - 进度条
-(void)progressSliderAction:(UISlider *)slider
{
    //改变播放进度
    [self.player seekToTime:self.playerView.progressSlider.value];
}


#pragma mark - 歌曲id
-(void)setSong_id:(NSInteger)song_id
{
    _song_id = song_id;
    
    if (song_id == 0) {
        
    }
    else
    {
        [self playMusic];
    }
    if (_indexRow == 0) {
        
        self.playerView.upButton.enabled = NO;
        
    }
}

#pragma mark - 播放音乐
- (void)playMusic
{
    
    NSString *string = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/track/detail?device=iPhone&trackId=%ld", (long)self.song_id];
    
    NSLog(@"haha%ld",(long)self.song_id);
    
    // afn获取数据
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    NSString *url_string = string;
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        
        NSMutableDictionary *dictionary = responseObject;
        
        LJHAlbumModel *playData = [LJHAlbumModel modelWithDictionary:dictionary];
        
        [self.player play:playData.playUrl64];
        
#pragma mark - 记录播放过的音乐
        
        //先判断表里是否有这个
        
        [[LJHFMData shareFMDB] deleteByTrackId:playData.trackId];
        
        [[LJHFMData shareFMDB] insertTrackData:playData];
        
        
        //给playView赋值
        
        [self.playerView.backgroundImageView sd_setImageWithURL:[NSURL URLWithString:playData.coverLarge] placeholderImage:PLACEHOLDER];
        [self.playerView.musicImageView sd_setImageWithURL:[NSURL URLWithString:playData.coverLarge] placeholderImage:PLACEHOLDER];
        
        self.navigationItem.title = playData.title;
        [self.ownerAvator sd_setImageWithURL:[NSURL URLWithString:playData.smallLogo] placeholderImage:PLACEHOLDER];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [self.ownerAvator addGestureRecognizer:tap];
        self.uid = playData.uid;
        self.ownerName.text = playData.nickname;
        self.ownerInfo.text = playData.personInfo;
        
//      后台信息 注:不显示后台信息,后台播放就会默认消失!
        
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:playData.coverLarge]];
        UIImage *image = [UIImage imageWithData:data];
        [_dict setObject:playData.title forKey:MPMediaItemPropertyTitle];
        MPMediaItemArtwork * mArt = [[MPMediaItemArtwork alloc] initWithImage:image];
        [_dict setObject:mArt forKey:MPMediaItemPropertyArtwork];//创建字典存储图片和title

        
#pragma mark - 创建定时器
        
        self.playTimer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
        
        //通知按钮换图片
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeImage" object:[NSURL URLWithString:playData.coverLarge]];
        [[LJHPlayBtn shareButton].musicBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:playData.coverLarge] forState:UIControlStateNormal placeholderImage:PLACEHOLDER];
        [self.playerView.playButton setImage:[UIImage imageNamed:@"toolbar_pause_h_p@2x.png"] forState:UIControlStateNormal];
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];
    
}

#pragma mark - 定时器方法
-(void)track
{
    //    NSLog(@"====%@",self.player);
    
    self.playerView.progressSlider.maximumValue = self.player.duration;//音乐总共时长
    self.playerView.progressSlider.value = self.player.progress;//当前进度
    //    NSLog(@"%f", self.playerView.progressSlider.value);
    
    //当前时长progress
    NSInteger proMin = (NSInteger)self.player.progress / 60;//当前秒
    NSInteger proSec = (NSInteger)self.player.progress % 60;//当前分钟
    
    //duration 总时长
    NSInteger durMin = (NSInteger)self.player.duration / 60;//总秒
    NSInteger durSec = (NSInteger)self.player.duration % 60;//总分钟
    
    self.playerView.timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", (long)proMin, (long)proSec, (long)durMin, (long)durSec];
    //    NSLog(@"proMin = %ld proSec = %ld",proMin, proSec);
    
    //    self.playerView.progressSlider
    
    //    后台进度条  (插入也写里面.因为图片和文字,.我是在,解析数据的时候赋值的)
    [self.dict setObject:[NSNumber numberWithInt:self.player.progress] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    [self.dict setObject:[NSNumber numberWithInt:self.player.duration] forKey:MPMediaItemPropertyPlaybackDuration];
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:_dict];
    
    
    
    if ((NSInteger)self.playerView.progressSlider.value + 1 == (NSInteger)self.playerView.progressSlider.maximumValue)
        
        
    {
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"playMode"] isEqualToString:@"顺序播放"])
        {
            [self nextButtonAction:nil];
        }
        else if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"playMode"] isEqualToString:@"单曲循环"])
        {
            
            [self playMusic];
            
        }
        else if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"playMode"] isEqualToString:@"随机播放"])
        {

            self.indexRow = arc4random()%(self.allMusicArray.count+1);
            
            LJHTrackModel *singleM = [self.allMusicArray objectAtIndex:self.indexRow];
            NSLog(@"%ld", (long)singleM.trackId);
            self.song_id = singleM.trackId;
            
            
        }
        
        
        
    }
}


-(void)viewWillDisappear:(BOOL)animated
{
   
    [self.navigationController removeFromParentViewController];
    
}







/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
